#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 当前模块导入home蓝图对象
from . import home
from flask import render_template, redirect, url_for, flash, session, request
# 导入表单
from app.home.forms import RegisterForm, LoginForm, UserdetailForm, PwdForm, CommentForm
# 导入模型
from app.models import User, Userlog, Preview, Tag, Movie, Comment, Moviecol

# 导入数据库连接
from app import db

# 导入密码加密工具
from werkzeug.security import generate_password_hash

# 导入唯一标识符
import uuid

# 装饰器
from functools import wraps

# 导入安全的文件名
from werkzeug.utils import secure_filename

from app.admin.views import change_filename

from app import app

# 上传路径不存在则生成
import os


# 定义前台登录权限的装饰器
def user_login_req(f):
    @wraps(f)
    def decorated_fun(*args, **kwargs):
        if 'user' not in session:
            return redirect(url_for("home.login", next=request.url))
        return f(*args, **kwargs)

    return decorated_fun


@home.route("/<int:page>/", methods=['GET'])  # 首页路由
def index(page=None):
    tags = Tag.query.all()
    page_data = Movie.query

    # 获取标签id
    tid = request.args.get("tid", 0)
    if int(tid) != 0:
        page_data = page_data.filter_by(tag_id=tid)
    # 星级
    star = request.args.get("star", 0)
    if int(star) != 0:
        page_data = page_data.filter_by(star=int(star))
    # 上映时间
    time = request.args.get("tid", 0)  # 最近 1 更早 2
    if int(time) != 0:
        if int(time) == 1:
            page_data = page_data.order_by(
                Movie.addtime.desc()
            )
        else:
            page_data = page_data.order_by(
                Movie.addtime.asc()
            )
    # 播放次数
    pm = request.args.get("pm", 0)  # play time 1高 2低
    if int(pm) != 0:
        if int(pm) == 1:
            page_data = page_data.order_by(
                Movie.playnum.desc()
            )
        else:
            page_data = page_data.order_by(
                Movie.playnum.asc()
            )
    # 评论次数
    cm = request.args.get("cm", 0)
    if int(cm) != 0:
        if int(cm) == 1:
            page_data = page_data.order_by(
                Movie.commentnum.desc()
            )
        else:
            page_data = page_data.order_by(
                Movie.commentnum.asc()
            )
    if page is None:
        page = 1
    # page = request.args.get("page",1)    get 获取
    page_data = page_data.paginate(page=int(page), per_page=12)
    p = dict(
        tid=tid,
        star=star,
        time=time,
        pm=pm,
        cm=cm
    )
    return render_template("home/index.html", tags=tags, p=p, page_data=page_data)


@home.route("/login/", methods=['GET', 'POST'])
def login():
    # print(session)
    form = LoginForm()
    if form.validate_on_submit():
        data = form.data
        user = User.query.filter_by(name=data["name"]).first()
        if not user.check_pwd(data['pwd']):
            flash("密码错误", "error")
            return redirect(url_for("home.login"))
        session['user'] = user.name
        session['user_id'] = user.id
        user_log = Userlog(
            user_id=user.id,
            #ip=request.remote_addr,
            ip=request.headers['X-Forwarded-For']
        )
        db.session.add(user_log)
        db.session.commit()
        return redirect(url_for("home.index", page=1))
    return render_template("home/login.html", form=form)


@home.route("/logout/")
def logout():
    session.pop("user", None)
    session.pop("user_id", None)
    return redirect(url_for("home.login"))  # home下的login 视图


@home.route("/register/", methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        user_data = User(
            name=data['name'],
            pwd=generate_password_hash(data['pwd']),
            email=data['email'],
            phone=data['phone'],
            uuid=uuid.uuid4().hex
        )
        db.session.add(user_data)
        db.session.commit()
        flash("注册成功,请登录", "ok")
        return redirect(url_for("home.login"))
    return render_template("home/register.html", form=form)


@home.route("/user/", methods=['GET', 'POST'])  # 会员中心,修改资料
@user_login_req
def user():
    form = UserdetailForm()
    user_data = User.query.get(int(session['user_id']))
    # 不校验图片
    form.avatar.validators = []
    if request.method == "GET":
        form.name.data = user_data.name
        form.email.data = user_data.email
        form.phone.data = user_data.phone
        form.info.data = user_data.info

    if form.validate_on_submit():
        data = form.data
        if not os.path.exists(app.config['AVATAR_DIR']):
            os.makedirs(app.config['AVATAR_DIR'])
            os.chmod(app.config['AVATAR_DIR'], 766)
        if form.avatar.data != "":
            file_avatar = secure_filename(form.avatar.data.filename)
            # 修改数据库用户头像
            user_data.avatar = change_filename(file_avatar)
            form.avatar.data.save(app.config['AVATAR_DIR'] + user_data.avatar)
        # 判断用户名,手机号,邮箱不能重复
        user_count = user_data.query.filter_by(name=data['name']).count()
        if user_data.name != data['name'] and user_count == 1:
            flash("用户名已存在", 'error')
            return redirect(url_for("home.user"))
        phone_count = user_data.query.filter_by(phone=data['phone']).count()
        if user_data.phone != data['phone'] and phone_count == 1:
            flash("手机号已存在", 'error')
            return redirect(url_for("home.user"))
        email_count = user_data.query.filter_by(email=data['email']).count()
        if user_data.email != data['email'] and email_count == 1:
            flash("邮箱已存在", 'error')
            return redirect(url_for("home.user"))
        user_data.name = data['name']
        user_data.email = data['email']
        user_data.phone = data['phone']
        user_data.info = data['info']
        db.session.add(user_data)
        db.session.commit()
        flash("保存 成功", 'ok')
        return redirect(url_for("home.user"))
    return render_template("home/user.html", form=form, user_data=user_data)


@home.route("/modify_password/", methods=['GET', 'POST'])
@user_login_req
def modify_password():
    form = PwdForm()
    if form.validate_on_submit():
        data = form.data
        user_object = User.query.filter_by(name=session['user']).first()
        if not user_object.check_pwd(data['old_pwd']):
            flash("原始密码输入错误", 'error')
            return redirect(url_for("home.modify_password"))
        user_object.pwd = generate_password_hash(data['new_pwd'])
        db.session.add(user_object)
        db.session.commit()
        flash("修改成功，请重新登录", 'ok')
        return redirect(url_for("home.logout"))
    return render_template("home/modify_password.html", form=form)


@home.route("/comments/<int:page>/")  # 用户评论记录
@user_login_req
def comments(page):
    if page is None:
        page = 1
    page_data = Comment.query.join(
        Movie
    ).join(
        User
    ).filter(
        Movie.id == Comment.movie_id,
        User.id == int(session['user_id'])
    ).order_by(
        Comment.addtime.desc()
    ).paginate(page=page, per_page=5)
    return render_template("home/comments.html", page_data=page_data)


@home.route("/loginlogs/<int:page>/", methods=['GET'])  # 登录日志
@user_login_req
def loginlogs(page):
    if page is None:
        page = 1
    page_data = Userlog.query.filter_by(
        user_id=int(session['user_id'])
    ).order_by(
        Userlog.logintime.desc()
    ).paginate(page=page, per_page=5)
    return render_template("home/loginlog.html", page_data=page_data)


@home.route("/collections/add/", methods=['POST'])  # 添加用户的电影收藏
@user_login_req
def collections_add():
    if request.method == 'POST':
        mid = request.form['mid']
        uid = request.form['uid']
        col_count = Moviecol.query.filter_by(
            movie_id=int(mid),
            user_id=int(uid)
        ).count()
        if col_count == 1:      # 已存在,删除
            collection = Moviecol.query.filter(
                Moviecol.movie_id == int(mid),
                Moviecol.user_id == int(uid)
            ).first()
            db.session.delete(collection)
            db.session.commit()
            data = dict(code=0)
        if col_count == 0:      # 不存在，添加
            moviecol = Moviecol(
                movie_id=int(mid),
                user_id=int(uid)
            )
            data = dict(code=1)
            db.session.add(moviecol)
            db.session.commit()
    import json
    return json.dumps(data)


@home.route("/collections/<int:page>/")  # 用户的电影收藏
@user_login_req
def collections(page=None):
    if page is None:
        page = 1
    page_data = Moviecol.query.join(
        Movie
    ).join(
        User
    ).filter(
        Movie.id == Moviecol.movie_id,
        User.id == int(session['user_id'])
    ).order_by(
        Moviecol.addtime.desc()
    ).paginate(page=page, per_page=10)
    return render_template("home/collections.html",page_data=page_data)


@home.route("/animation/")  # 动画页面  预告
def animation():
    data = Preview.query.all()
    return render_template("home/animation.html", data=data)


@home.route("/search/<int:page>/")  # 搜索页面
def search(page=None):
    if page is None:
        page = 1
    # 获取搜索关键字
    key = request.args.get("key", "")
    movie_count = Movie.query.filter(
        Movie.title.ilike('%' + key + '%')
    ).count()
    page_data = Movie.query.filter(
        Movie.title.ilike('%' + key + '%')
    ).order_by(
        Movie.addtime.desc()
    ).paginate(page=page, per_page=10)
    # 搜索界面分页传递 搜索关键字
    page_data.key = key
    return render_template("home/search.html", key=key, page_data=page_data, movie_count=movie_count)


@home.route("/play/<int:id>/<int:page>/", methods=['GET', 'POST'])  # 详情页面
def play(id=None, page=None):
    if id is None:
        id = 1
    # 查询电影信息
    movie = Movie.query.join(
        Tag
    ).filter(
        Tag.id == Movie.tag_id,
        Movie.id == id
    ).first_or_404()

    if page is None:
        page = 1
    page_data = Comment.query.join(
        Movie
    ).join(
        User
    ).filter(
        # Comment.movie_id == movie.id
        Movie.id == movie.id,
        Comment.user_id == User.id
    ).order_by(
        Comment.addtime.desc()
    ).paginate(page=page, per_page=10)

    movie.playnum = movie.playnum + 1
    form = CommentForm()
    # 提交用户电影评论
    if "user" in session and form.validate_on_submit():
        data = form.data
        comment = Comment(
            content=data['content'],
            movie_id=id,
            user_id=session['user_id']
        )
        db.session.add(comment)
        db.session.commit()
        # 修改电影播放次数

        movie.commentnum = movie.commentnum + 1
        db.session.add(movie)
        db.session.commit()
        flash("评论成功", 'ok')
        return redirect(url_for('home.play', id=movie.id, page=1))
    db.session.add(movie)
    db.session.commit()
    if "user" in session :
        col_count = Moviecol.query.filter_by(
            movie_id=id,
            user_id=int(session['user_id'])
        ).count()
    else:
        col_count = 0
    return render_template("home/play.html", movie=movie, form=form, page_data=page_data,col_count=col_count)


@home.route("/video/<int:id>/<int:page>/", methods=['GET', 'POST'])  # 弹幕播放页面
def video(id=None, page=None):
    if id is None:
        id = 1
    # 查询电影信息
    movie = Movie.query.join(
        Tag
    ).filter(
        Tag.id == Movie.tag_id,
        Movie.id == id
    ).first_or_404()

    if page is None:
        page = 1
    page_data = Comment.query.join(
        Movie
    ).join(
        User
    ).filter(
        # Comment.movie_id == movie.id
        Movie.id == movie.id,
        Comment.user_id == User.id
    ).order_by(
        Comment.addtime.desc()
    ).paginate(page=page, per_page=10)

    movie.playnum = movie.playnum + 1
    form = CommentForm()
    # 提交用户电影评论
    if "user" in session and form.validate_on_submit():
        data = form.data
        comment = Comment(
            content=data['content'],
            movie_id=id,
            user_id=session['user_id']
        )
        db.session.add(comment)
        db.session.commit()
        # 修改电影播放次数

        movie.commentnum = movie.commentnum + 1
        db.session.add(movie)
        db.session.commit()
        flash("评论成功", 'ok')
        return redirect(url_for('home.video', id=movie.id, page=1))
    db.session.add(movie)
    db.session.commit()
    col_count = Moviecol.query.filter_by(
        movie_id=id,
        user_id=int(session['user_id'])
    ).count()
    return render_template("home/video.html", movie=movie, form=form, page_data=page_data,col_count=col_count)
